<template>
    <div class="app-container">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="客户名称">
                        <el-input v-model="queryParams.criteria.customerName" style="width: 250px;"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="客户类型">
                        <el-input v-model="queryParams.criteria.customerType" style="width: 250px;"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="驾驶员名称">
                        <el-input v-model="queryParams.criteria.driverName" style="width: 250px;"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="合作类型">
                        <el-input v-model="queryParams.criteria.driverType" style="width: 250px;"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="车牌号">
                        <el-input v-model="queryParams.criteria.plateNo" style="width: 250px;"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="案件时间">
                        <el-date-picker
                                style="width: 250px;"
                                v-model="dateRanges"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                >导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        icon="el-icon-download"
                        size="mini"
                        @click="handleExport"
                >导出</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="orderList">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="案件日期" align="center" prop="createdDate" width="100">
                <template slot-scope="scope">
                    <span>{{ formatDate(scope.row.collectionDate, 'yyyy-MM-dd') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="车牌号" align="center" prop="plateNo" width="100"/>
            <el-table-column label="客户名称" align="center" prop="customerName" width="220"/>
            <el-table-column label="客户类型" align="center" prop="customerType" width="120"/>
            <el-table-column label="驾驶员名称" align="center" prop="driverName" width="120"/>

            <el-table-column label="合作类型" align="center" prop="driverType" width="120"/>
            <el-table-column label="挂账总金额" align="center" prop="guaZhangAmount" width="120"/>
            <el-table-column label="折扣金额" align="center" prop="duiZhangAmount" width="120"/>
            <el-table-column label="加公里数金额及差额" align="center" prop="gongLiAmount" width="160"/>
            <el-table-column label="差额备注" align="center" prop="chaDesc" width="160"/>

            <el-table-column label="应收金额" align="center" prop="totalAmount" width="120"/>
            <el-table-column label="还款金额" align="center" prop="backAmount" width="120"/>
            <el-table-column label="未收金额" align="center" prop="waitPayAmount" width="120"/>
            <el-table-column label="还款日期记录" align="center" prop="backDate" width="140"/>
            <el-table-column label="备注" align="center" prop="comments" width="100"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="scope">
                    <el-button
                            size="small"
                            type="primary"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.row)"
                    >编辑
                    </el-button>

                    <el-button
                            size="small"
                            type="success"
                            icon="el-icon-tickets"
                            @click="handleDetail(scope.row)"
                    >详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageDto.pageNum"
                :limit.sync="queryParams.pageDto.pageSize"
                @pagination="getList"
        ></pagination>

        <div style="margin-bottom: 20px" v-if="total>0">
            总应收金额：{{pageTotalAmount}}，总还款金额：{{pageBackAmount}}，总未收金额：{{pageWaitPayAmount}}
        </div>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px">
            <el-form ref="form" label-width="100px">
                <el-form-item label="文件">
                    <el-upload
                            :limit=1
                            :auto-upload="false"
                            accept=".xlsx"
                            :action="UploadUrl()"
                            :before-upload="beforeUploadFile"
                            :on-change="fileChange"
                            :on-exceed="exceedFile"
                            :on-success="handleSuccess"
                            :on-error="handleError"
                            :file-list="fileList">
                        <i class="el-icon-upload"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="uploadFile">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑" :visible.sync="ifEdit" width="600px">
            <el-form ref="editForm" :model="editForm" :rules="rules" label-width="150px">
                <el-form-item label="折扣金额" prop="duiZhangAmount">
                    <el-input-number v-model="editForm.duiZhangAmount" :step="0.01" style="width: 400px"/>
                </el-form-item>
                <el-form-item label="加公里数金额及差额" prop="gongLiAmount">
                    <el-input-number v-model="editForm.gongLiAmount" :step="0.01" style="width: 400px"/>
                </el-form-item>
                <el-form-item label="差额备注" prop="chaDesc">
                    <el-input v-model="editForm.chaDesc" style="width: 400px"/>
                </el-form-item>
                <el-form-item label="还款金额" prop="backAmount">
                    <el-input-number v-model="editForm.backAmount" :step="0.01" style="width: 400px"/>
                </el-form-item>
                <el-form-item label="还款时间" prop="backDate">
                    <el-input v-model="editForm.backDate" style="width: 400px"/>
                </el-form-item>
                <el-form-item label="备注" prop="comments">
                    <el-input v-model="editForm.comments" placeholder="请输入备注" style="width: 400px"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancelEdit">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import { formatDate } from '@/utils/dateUtil'
  import { getPage, uploadExcel ,updateOrder,countPageAmount} from '@/api/collectionOrder'
  import {exportCollectionOrder} from '@/api/exportApi'
  export default {
    name: 'index',
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        isEdit: false,
        // 类型数据字典
        typeOptions: [],
        orderList: [],
        // 查询参数
        queryParams: {
          pageDto: {
            pageNum: 1,
            pageSize: 20
          },
          criteria: {},
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        fileList: [],
        pageTotalAmount:0.00,
        pageBackAmount:0.00,
        pageWaitPayAmount : 0.00,
        dateRanges:[],
        ifEdit:false,
        editForm:{},
      }
    },
    created() {
      this.getList()

    },
    methods: {
      formatDate,
      /** 查询参数列表 */
      getList(val) {
        this.loading = true
        if(this.dateRanges && this.dateRanges.length>0){
          this.queryParams.criteria.dateRange= {
            startTime:formatDate(this.dateRanges[0]),
            endTime:formatDate(this.dateRanges[1])
          }
        }
        if(val){
          this.queryParams.pageDto.pageNum = val.page;
          this.queryParams.pageDto.pageSize = val.limit;
        }
        getPage(this.queryParams).then(response => {
            this.orderList = response.result.list
            this.total = response.result.total
            this.loading = false
          }
        )
        countPageAmount(this.queryParams.criteria).then(resp=>{
          if(!resp.hasError){
            this.pageTotalAmount = resp.result.pageTotalAmount.toFixed(2);
            this.pageBackAmount = resp.result.pageBackAmount.toFixed(2);
            this.pageWaitPayAmount =resp.result.pageWaitPayAmount.toFixed(2);
          }
        })
      },
      handleEdit(row){
        this.ifEdit = true;
        this.editForm = row;
      },
      UploadUrl() {
        return ''
      },
      handleExport(){
        exportCollectionOrder(this.queryParams.criteria).then(response=>{
          if(!response.hasError){
            if(response.message){
              this.$message({
                type: 'info',
                message: response.message
              })
            }else{
              let exportUrl = response.result.exportUrl;
              window.open(process.env.BASE_API +exportUrl , '_blank')
            }
          }else{
            this.$message({
              type: 'error',
              message: '生成导出文件失败,请稍候再试!'
            })
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.fileList = []
      },
      cancelEdit(){
        this.ifEdit = false;
        this.editForm = {};
      },
      submitForm(){
        let formData = {
          ...this.editForm,
        }
        updateOrder(formData).then(resp=>{
          if(!resp.hasError){
            this.cancelEdit();
            this.getList();
          }else{
            this.$message.error(resp.message);
          }
        })
      },
      handleDetail(row){
        const { collectionId } = row
        sessionStorage.setItem('collectionId', row.collectionId);
        this.$router.push('/finance/collectionorder/detail')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageDto.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRanges = []
        this.queryParams ={
          pageDto: {
            pageNum: 1,
              pageSize: 20
          },
          criteria: {},
        };
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.title = '上传文件'
        this.open = true
        this.isEdit = false
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.collectionId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      exceedFile(files, fileList) {
        this.$message.error('选择多个文件！')
      },
      fileChange(file, fileList) {
        this.fileList.push(file.raw)
      },
      beforeUploadFile(file) {
        let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
        let size = file.size / 1024 / 1024
        if (extension !== 'xlsx') {
          this.$message.error('只能上传后缀是.xlsx的文件！')
        }
        if (size > 4) {
          this.$message.error('文件大小不得超过4M！')
        }
      },
      // 文件上传成功时的钩子
      handleSuccess(res, file, fileList) {
        this.$message.success('文件上传成功！')
      },
      // 文件上传失败时的钩子
      handleError(err, file, fileList) {
        this.$message.error('文件上传失败！')
      },
      uploadFile() {
        if (this.fileList.length === 0) {
          this.$message.error('请上传文件！')
        } else {
          let form = new FormData()
          form.append('file', this.fileList[0])
          uploadExcel(form).then(resp => {
            if (!resp.hasError) {
              this.$message.success('文件上传成功！')
              this.cancel()
              this.getList()
            } else {
              this.$message.error(resp.message)
            }
          })
        }
      }
    }
  }
</script>

<style scoped>

</style>
